package com.hmdp.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopTypeMapper shopTypeMapper;

    @Override
    public List<ShopType> queryTypeList() {
        // 1. 访问redis
        String key = "shopTypeList:cache";
        String shopTypeListJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopTypeListJSON)) {
            List<ShopType> shopTypes = JSONUtil.toBean(
                    shopTypeListJSON,
                    new TypeReference<List<ShopType>>() {},
                    false);
            return shopTypes;
        }
        // 2. 访问数据库
        List<ShopType> shopTypes = shopTypeMapper.selectList(null);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypes));
        // 3. 返回数据
        return shopTypes;
    }
}
